package goodenglish.application.impl;

import goodenglish.application.LexiconEditService;
import goodenglish.domain.model.lexicon.Lexicon;
import goodenglish.domain.model.lexicon.LexiconRepository;
import goodenglish.domain.model.profword.ProfWordLib;
import goodenglish.domain.model.profword.ProfWordLibRepository;
import goodenglish.domain.service.ServiceException;
import goodenglish.infrastructure.repository.db.LexiconRepositoryDb;
import goodenglish.infrastructure.repository.db.ProfWordLibRepositoryDb;
import goodenglish.infrastructure.repository.db.TransactionManager;
import goodenglish.interfaces.BeanFactory;

import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LexiconEditServiceImpl implements LexiconEditService {
	private static Log logger = LogFactory.getLog(LexiconEditServiceImpl.class);

	/**
	 * 更改字幕关联生词
	 * 
	 * @param subt
	 * @param rememberSpells
	 */
	@Override
	public void changeNewWords(Lexicon lexicon, Set<String> rememberSpells) {
		ProfWordLib profWords = profWordsRepository.getProfWordLib();
		for (String rememberSpell : rememberSpells) {
			lexicon.removeWord(rememberSpell);

			profWords.addProfWord(rememberSpell);

		}
		TransactionManager transactionManager = TransactionManager.getTranManager();
		try {
			transactionManager.beginTransaction();
			lexiconRepository.updateLexion(lexicon);
			profWordsRepository.addOrUpdateProfWordLib(profWords);
		} catch (Exception e) {
			transactionManager.rollback();
			e.printStackTrace();
			throw new ServiceException("更新单词时出错", e);
		}

	}

	/**
	 * 修改单词解释
	 * 
	 * @param wordSpell
	 * @param explain
	 */
	public void editNewWord(Lexicon lexicon, String spell, String explain) {
		// 如果拼写为空，则返回
		if (spell == null || spell.trim().equals("")) {
			return;
		}
		lexicon.editNewWordExplain(spell, explain);
		lexiconRepository.updateLexion(lexicon);

	}

	private ProfWordLibRepository profWordsRepository = BeanFactory.getSingleInstance(ProfWordLibRepositoryDb.class);
	private LexiconRepository lexiconRepository = BeanFactory.getSingleInstance(LexiconRepositoryDb.class);

}
